import axios, {AxiosRequestConfig} from "axios";
import HttpCode from "./httpCode";
import tokenApi from "./tokenApi";
import {Layer} from "slash-layer";
import SlashAppContext from "@/context/SlashAppContext";
import {ref} from "vue";

axios.defaults.timeout = 1000 * 30;
axios.defaults.baseURL = "http://192.168.35.181:8889/api";
/** 请求拦截器
 *  在header添加authorization
 * */

axios.interceptors.request.use(function (param: AxiosRequestConfig) {
  if (param.headers) {
    param.headers["authorization"] = tokenApi.getToken();
    param.headers["requestId"] = createUUID();
  }
  return param;
}, function (error: any) {
  // 请求错误
  return Promise.reject(error);
});

function createUUID() {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }

  return "WEB-" + (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4()).toUpperCase();
}


/**
 * 封装GET和POST方法
 * @type {{doPost: (function(*=, *=): Promise<AxiosResponse<T>>), doGet: (function(*=, *=): Promise<AxiosResponse<T>>)}}
 */
export const appAxios = axios.create({
  timeout: 1000 * 30
});

/**
 * 下载文件流的api
 */
export const streamAxios = axios.create({
  timeout: 1000 * 30
});

appAxios.interceptors.response.use(async function (response: { config: any, data: any; status: any }) {
  const msg = response.data;
  switch (msg.code) {
    case HttpCode.OK: {
      return msg;
    }
    case HttpCode.E600: {
      SlashAppContext.getRouter()?.push({
        path: SlashAppContext.getAppConfig().loginPath
      });
      break;
    }
    default: {
      try {
        Layer.error(msg.msg);
      } catch (e) {
        console.warn(e);
      }
      return Promise.reject(msg);
    }
  }

}, (error => {
  console.error(error);
  try {
    Layer.error(error.message);
  } catch (e) {
    console.warn(e)
  }
  // 请求错误
  // return Promise.reject({
  //   code: HttpCode.Fail,
  //   msg: error.message,
  //   data: error
  // });
}));

appAxios.interceptors.request.use(function (param: AxiosRequestConfig) {
  if (param.headers) {
    param.headers["authorization"] = tokenApi.getToken();
    param.headers["requestId"] = createUUID();
  }
  return param;
}, function (error: any) {
  console.error(error);
  // 请求错误
  return Promise.reject({
    code: HttpCode.Fail,
    msg: error.message,
    data: error
  });
});

streamAxios.interceptors.response.use(async function (response: { config: any, data: any; status: any }) {
  return response.data;
}, (error => {
  console.error(error);
  try {
    Layer.error(error.message);
  } catch (e) {
    console.warn(e)
  }
}));

streamAxios.interceptors.request.use(function (param: AxiosRequestConfig) {
  if (param.headers) {
    param.headers["authorization"] = tokenApi.getToken();
    param.headers["requestId"] = createUUID();
  }
  return param;
}, function (error: any) {
  console.error(error);
  // 请求错误
  return Promise.reject({
    code: HttpCode.Fail,
    msg: error.message,
    data: error
  });
});

// @ts-ignore
const Api = {
  doPost: (url: string, data?: any, headers?: any): Promise<any> => {
    return appAxios.post(url, data, {
      baseURL: SlashAppContext.getBaseUrl(),
      headers: headers
    });
  },
  doGet: (url: string, data?: any, headers?: any): Promise<any> => {
    console.log("请求参数:", data);
    return appAxios.get(url, {
      baseURL: SlashAppContext.getBaseUrl(),
      params: {...data},
      headers: headers
    });
  },
  getBaseUrl: (): string | undefined => {
    return SlashAppContext.getBaseUrl();

  },
  doOpen: (url: string, data?: any) => {
    window.open(Api.getBaseUrl() + url + "?" + Api.jsonToUrl(data));
  },
  doOpenByToken: (url: string, data?: any) => {
    if (!data) {
      data = {};
    }
    data["token"] = tokenApi.getToken();
    return Api.doOpen(url, data);
  },
  jsonToUrl(json: any) {
    const uri = Object.keys(json).map(function (key) {
      return encodeURIComponent(key) + "=" + encodeURIComponent(json[key]);
    }).join("&");
    return uri;
  },
  doUpload: (url: string, formData: FormData): Promise<any> => {
    if (!url) {
      url = SlashAppContext.getAppConfig().fileUploadUri;
    }
    const fileBaseUrl = SlashAppContext.fileBaseUrl();
    console.log("文件上传路径", fileBaseUrl);
    return appAxios.post(url, formData, {
      baseURL: fileBaseUrl,
      timeout: 1000 * 30 * 60,
      headers: {
        "Content-type": "multipart/form-data"
      }
    });
  },
  /** 请求文件流的post方法 */
  doStreamPost: (url: string, data?: any, headers?: any): Promise<any> => {
    return streamAxios.post(url, data, {
      baseURL: SlashAppContext.getBaseUrl(),
      headers: headers
    });
  },
  /** 请求文件流的get方法 */
  doStreamGet: (url: string, data?: any, headers?: any): Promise<any> => {
    return streamAxios.get(url, {
      baseURL: SlashAppContext.getBaseUrl(),
      params: {...data},
      headers: headers
    });
  }
};
// export const asyncApi = (api: () => Promise<any>) => {
//   const obj = ref<any>();
//   if (typeof api != "undefined") {
//     api().then((msg) => {
//       obj.value = msg;
//     });
//   }
//   return obj;
// };
export const asyncApi = (api: () => Promise<any>) => {
  return function () {
    const obj = ref<any>();
    if (typeof api != "undefined") {
      api().then((msg) => {
        obj.value = msg;
      });
    }
    return obj;
  };
};
export default Api;
